document.addEventListener('DOMContentLoaded', () => {
    const { createApp, ref, computed, watch, nextTick } = Vue;
    
    const app = createApp({
    setup() {
        // 表格列定义
        const columns = [
            { key: 'id', label: 'ID' },
            { key: 'name', label: '姓名' },
            { key: 'email', label: '邮箱' },
            { key: 'date', label: '日期' },
            { key: 'status', label: '状态' }
        ];
        
        // 示例数据
        const data = ref([
            { id: 1, name: '张三', email: 'zhangsan@example.com', date: '2023-05-15', status: 'Active' },
            { id: 2, name: '李四', email: 'lisi@example.com', date: '2023-05-16', status: 'Inactive' },
            { id: 3, name: '王五', email: 'wangwu@example.com', date: '2023-05-17', status: 'Pending' },
            { id: 4, name: '赵六', email: 'zhaoliu@example.com', date: '2023-05-18', status: 'Active' },
            { id: 5, name: '钱七', email: 'qianqi@example.com', date: '2023-05-19', status: 'Active' },
            { id: 6, name: '孙八', email: 'sunba@example.com', date: '2023-05-20', status: 'Inactive' },
            { id: 7, name: '周九', email: 'zhoujiu@example.com', date: '2023-05-21', status: 'Pending' },
            { id: 8, name: '吴十', email: 'wushi@example.com', date: '2023-05-22', status: 'Active' },
            { id: 9, name: '郑十一', email: 'zhengshiyi@example.com', date: '2023-05-23', status: 'Inactive' },
            { id: 10, name: '王十二', email: 'wangshier@example.com', date: '2023-05-24', status: 'Active' },
            { id: 11, name: '李十三', email: 'lishisan@example.com', date: '2023-05-25', status: 'Pending' },
            { id: 12, name: '张十四', email: 'zhangshisi@example.com', date: '2023-05-26', status: 'Active' },
            { id: 13, name: '刘十五', email: 'liushiwu@example.com', date: '2023-05-27', status: 'Inactive' },
            { id: 14, name: '陈十六', email: 'chenshiliu@example.com', date: '2023-05-28', status: 'Active' },
            { id: 15, name: '杨十七', email: 'yangshiqi@example.com', date: '2023-05-29', status: 'Pending' }
        ]);

        // 状态选项
        const statusOptions = ['Active', 'Inactive', 'Pending'];
        
        // 搜索和排序状态
        const searchQuery = ref('');
        const sortKey = ref('id');
        const sortOrder = ref('asc');
        const statusFilter = ref('');
        
        // 分页状态
        const currentPage = ref(1);
        const pageSize = ref(5);
        const pageSizes = [5, 10, 15, 20];

        // 编辑和删除状态
        const showEditModal = ref(false);
        const showDeleteModal = ref(false);
        const editingItem = ref(null);
        const deletingItem = ref(null);

        // 通知状态
        const showNotification = ref(false);
        const notificationMessage = ref('');
        const notificationType = ref('success');

        // 显示通知
        const showNotificationMessage = (message, type = 'success') => {
            notificationMessage.value = message;
            notificationType.value = type;
            showNotification.value = true;
            setTimeout(() => {
                showNotification.value = false;
            }, 3000);
        };
        
        // 过滤后的数据
        const filteredData = computed(() => {
            let result = data.value;
            
            if (statusFilter.value) {
                result = result.filter(item => item.status === statusFilter.value);
            }
            
            if (searchQuery.value) {
                const query = searchQuery.value.toLowerCase();
                result = result.filter(item => {
                    return Object.values(item).some(
                        value => String(value).toLowerCase().includes(query)
                    );
                });
            }
            
            return result;
        });
        
        // 排序后的数据
        const sortedData = computed(() => {
            return [...filteredData.value].sort((a, b) => {
                let aValue = a[sortKey.value];
                let bValue = b[sortKey.value];
                
                if (typeof aValue === 'string' && typeof bValue === 'string') {
                    aValue = aValue.toLowerCase();
                    bValue = bValue.toLowerCase();
                }
                
                if (aValue < bValue) {
                    return sortOrder.value === 'asc' ? -1 : 1;
                }
                if (aValue > bValue) {
                    return sortOrder.value === 'asc' ? 1 : -1;
                }
                return 0;
            });
        });
        
        // 分页数据
        const paginatedData = computed(() => {
            const startIndex = (currentPage.value - 1) * pageSize.value;
            const endIndex = startIndex + pageSize.value;
            return sortedData.value.slice(startIndex, endIndex);
        });
        
        // 总页数
        const totalPages = computed(() => {
            return Math.ceil(filteredData.value.length / pageSize.value);
        });
        
        // 监听过滤器变化，重置到第一页
        watch([searchQuery, pageSize, statusFilter], () => {
            currentPage.value = 1;
        });
        
        // 排序方法
        const sortBy = (key) => {
            if (sortKey.value === key) {
                sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
            } else {
                sortKey.value = key;
                sortOrder.value = 'asc';
            }
        };
        
        // 获取排序类
        const getSortClass = (key) => {
            if (sortKey.value !== key) return '';
            return sortOrder.value === 'asc' ? 'sorted-asc' : 'sorted-desc';
        };
        
        // 分页方法
        const prevPage = () => {
            if (currentPage.value > 1) {
                currentPage.value--;
            }
        };
        
        const nextPage = () => {
            if (currentPage.value < totalPages.value) {
                currentPage.value++;
            }
        };
        
        const goToPage = (page) => {
            currentPage.value = page;
        };
        
        const handleSearch = () => {
            currentPage.value = 1;
        };
        
        const handlePageSizeChange = () => {
            currentPage.value = 1;
        };

        // 编辑方法
        const editItem = (item) => {
            editingItem.value = { ...item };
            showEditModal.value = true;
        };

        const closeEditModal = () => {
            showEditModal.value = false;
            editingItem.value = null;
        };

        const saveEdit = () => {
            const index = data.value.findIndex(item => item.id === editingItem.value.id);
            if (index !== -1) {
                data.value[index] = { ...editingItem.value };
                showNotificationMessage('数据已成功更新');
            }
            closeEditModal();
        };

        // 删除方法
        const confirmDelete = (item) => {
            deletingItem.value = item;
            showDeleteModal.value = true;
        };

        const closeDeleteModal = () => {
            showDeleteModal.value = false;
            deletingItem.value = null;
        };

        const confirmDeleteItem = () => {
            const index = data.value.findIndex(item => item.id === deletingItem.value.id);
            if (index !== -1) {
                data.value.splice(index, 1);
                showNotificationMessage('数据已成功删除');
            }
            closeDeleteModal();
        };

        // 导出CSV
        const exportToCSV = () => {
            const headers = '序号,' + columns.map(col => col.label).join(',');
            const rows = data.value.map((item, index) => {
                const rowNum = index + 1;
                return `"${rowNum}",` + columns.map(col => `"${item[col.key]}"`).join(',');
            }).join('\n');
            
            const csvContent = `${headers}\n${rows}`;
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            
            link.setAttribute('href', url);
            link.setAttribute('download', 'table-data.csv');
            link.style.visibility = 'hidden';
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            
            showNotificationMessage('数据已导出为CSV文件');
        };
        
        return {
            columns,
            searchQuery,
            sortKey,
            sortOrder,
            currentPage,
            pageSize,
            pageSizes,
            statusOptions,
            statusFilter,
            paginatedData,
            totalPages,
            showEditModal,
            showDeleteModal,
            editingItem,
            showNotification,
            notificationMessage,
            notificationType,
            sortBy,
            getSortClass,
            prevPage,
            nextPage,
            goToPage,
            handleSearch,
            handlePageSizeChange,
            editItem,
            closeEditModal,
            saveEdit,
            confirmDelete,
            closeDeleteModal,
            confirmDeleteItem,
            exportToCSV
        };
    }
});

    app.mount('#app');
});